//
//  ServerManger.swift
//  MAX-OSS
//
//  Created by 我演示 on 2019/11/8.
//  Copyright © 2019 ALLSall. All rights reserved.
//

import Cocoa

class ServerManger: NSObject {
    fileprivate lazy var serverSocket :TCPServer = TCPServer(addr: "0.0.0.0", port: 7878)
    
    fileprivate var isServerRunning : Bool = false
    
    fileprivate lazy var clientMrgs : [ClientManager] = [ClientManager]()
}

extension ServerManger {
    func startRunning() {
        //1: 创建serverSockert
      isServerRunning = true
        
        ///2: 开启监听
        serverSocket.listen()
        
        ///3: 开启接收客户端信息
        
            DispatchQueue.global().async {
                while true {
                    if let client = self.serverSocket.accept() {
                        DispatchQueue.global().async {
                            self.handleClient(client)
                        }
                        
                        self.handleClient(client)
                    }
                }
                
          
        }
        
    }
    
    // 停止
    func stopRunning() {
        
        isServerRunning = false
        
    }
    
}


extension ServerManger {
    fileprivate func handleClient(_ client : TCPClient) {
       /// 用一个clientMnanager 来管理TCPclient
        let mgr = ClientManager(tcpClient: client)
        
        //2: 保存数组
        clientMrgs.append(mgr)
        
        //3: 使用client 开始接受消息
        
        
    }
    
}
